package com.example.srm.common.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.srm.auth.mapper.TUserMapper;
import com.example.srm.auth.service.SysUserTokenService;
import com.example.srm.auth.service.TPermissionService;
import com.example.srm.constant.PermissionConstant;
import com.example.srm.constant.RedisConstant;
import com.example.srm.constant.UserConstant;
import com.example.srm.domain.SysUserToken;
import com.example.srm.domain.TUser;
import com.example.srm.domain.tree.Tree;
import com.example.srm.domain.vo.Result;
import com.example.srm.auth.service.TUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author pfk
 * @creatTime 2021/11/24 16:30
 * @describe    登录的接口
 */
@RestController
@Slf4j
@CrossOrigin
public class LoginController {

    @Autowired
    private TUserService userService;

    @Autowired
    private TUserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SysUserTokenService tokenService;

    @Autowired
    private TPermissionService permissionService;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Result login(@RequestBody TUser userVO, HttpServletRequest request,HttpServletResponse response)throws Exception{
        try {
            //参数校验
            if (userVO == null||userVO.getUserName()==null||userVO.getPassword()==null){return new Result().setCode(500).setMsg("用户名或密码为空");}
            //redis中取值
            HashOperations hashOperations = redisTemplate.opsForHash();
            TUser userinfo = (JSONObject.parseObject(JSONObject.toJSONString(hashOperations.get(RedisConstant.USER_INFO, userVO.getUserName().toString())),TUser.class));
            //获取数据库用户的盐
            if(userinfo==null){
                //从数据库取值
                userinfo = userService.getOne(new QueryWrapper<TUser>()
                        .eq(UserConstant.name,  userVO.getUserName()));
                //数据库查询到数据存到redis，没查到就不存---->保证redis里的是正确用户信息
                if (userinfo!=null){
                    hashOperations.put(RedisConstant.USER_INFO,userVO.getUserName().toString(),userinfo);
                    //设置redis2分钟过期过期
                    redisTemplate.expire(RedisConstant.USER_INFO,RedisConstant.EXPIRE_TIME, TimeUnit.SECONDS);
                }
            }
            //如果此时经过了redis和数据库仍然查不到用户-->用户不存在
            if (userinfo ==null){
                return new Result().setCode(500).setMsg("用户不存在");
            }
            //如果账号和密码都对不上 ->登录失败
            if(!(userinfo.getUserName().equals(userVO.getUserName())&&
                userinfo.getPassword().equals( new Md5Hash(userVO.getPassword(), userinfo.getSalt()).toString()))
            ){
                hashOperations.put(RedisConstant.USER_INFO,userVO.getUserName(),"");
                return new Result().setCode(500).setMsg("用户名或密码不正确~");
            }
            if ("0".equals(userinfo.getState())){
                return new Result().setCode(500).setMsg("用户被禁用");
            }

            //颁发token
            String userId = userinfo.getId();
            response.setHeader(PermissionConstant.AUTH_TOKEN,userId);
//            //创建存放账号信息的cookie
//            Cookie userCookie = new Cookie("USERINFO", userId.toString());
//            userCookie.setPath("/");
//
//            //存放账号信息与密钥加密后的结果值的cookie
//            String ssid = new Md5Hash(userId.toString(), PermissionConstant.SECRET_KEY).toString();
//            Cookie ssidCookie = new Cookie("SSID", ssid);
//            ssidCookie.setPath("/");
//
//            response.addCookie(userCookie);
//            response.addCookie(ssidCookie);


            boolean result = tokenService.createToken(userId);

            //获取用户所有权限的code存放到redis
            boolean redis = userService.updatePermissionForRedis(userinfo.getId());

            if ((!result)||(!redis)) {
                return new Result().setCode(500).setMsg("登录失败");
            }

            return new Result().setMsg("登录成功~").setData(userId).setSuccess(true);
        }catch (Exception e){
            log.error("登录出现错误~",e);
            return new Result().setCode(500).setMsg("登录失败");
        }
    }


    /**
     * 告诉前端请跳转登录页面
     * @param response
     * @return
     * @throws ServletException
     */
    @RequestMapping(value = "/toLogin", method = RequestMethod.GET)
    public Result toLogin(HttpServletResponse response) throws ServletException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        Result result =new Result().setCode(401).setMsg("请你先登录你的用户!");
        return result;
    }

    /**
     *  退出登录
     * @return
     */
    @GetMapping(value = "/loginOut")
    public Result logOut(HttpServletRequest request){
       try {
           HashOperations hashOperations = redisTemplate.opsForHash();
           String token = request.getHeader(PermissionConstant.AUTH_TOKEN);
           //逻辑删除用户token
           boolean result = tokenService.removeByToken(token);
           //删除redis中的用户缓存(2分钟后自动失效)
           //删除redis中的用户权限（12小时后自动过期）
       }catch (Exception e){
           log.error("退出操作出现了异常",e);
       }
        return new Result().setSuccess(true).setMsg("登出成功!");
    }


}
